package com.hwl.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwl.acl.mapper.RoleMapper;
import com.hwl.acl.mapper.UserRoleMapper;
import com.hwl.acl.pojo.Role;
import com.hwl.acl.pojo.UserRole;
import com.hwl.acl.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author long
 * @since 2021-10-16
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 获取该用户拥有的角色id
     *
     * @param userId 用户id
     * @return 角色id集合
     */
    private List<String> getRoleIds(String userId) {
        return userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", userId))
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> findRoleByUserId(String userId) {
        //所有的角色集合
        List<Role> allRoleList = baseMapper.selectList(null);

        //获取该管理员拥有的角色id
        List<String> roleIds = getRoleIds(userId);

        //该管理员拥有的角色
        List<Role> assignRoles = new ArrayList<>();
        for (Role role : allRoleList) {
            if (roleIds.contains(role.getId())) {
                assignRoles.add(role);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("assignRoles", assignRoles);
        map.put("allRolesList", allRoleList);
        return map;
    }

    @Override
    public int assigningRoles(String userId, String[] roleIds) {
        //先删除掉原有的角色再统一添加
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));

        return userRoleMapper.addRole(userId, roleIds);
    }

    @Override
    public List<Role> selectRoleByUserId(String id) {
        return baseMapper.selectBatchIds(getRoleIds(id));
    }
}
